package cn.likole.oj.module;


import cn.likole.oj.bean.Mail;
import cn.likole.oj.bean.User;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.plugins.apidoc.annotation.Api;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@IocBean
@At("mail")
@Filters(@By(type = CheckSession.class, args = {"uid", "/"}))
@Api(name = "站内信模块")
public class MailModule {

    @Inject
    protected Dao dao;

    @At
    @Ok("json:full")
    public Mail viewMail(@Param("vid")int id, HttpSession session){
        Mail mail=dao.fetch(Mail.class, Cnd.where("mailId","=",id).and("toUser","=",session.getAttribute("uid")));
        mail.setNewMail(false);
        dao.update(mail);
        return mail;
    }

    @At
    public Object sendMail(@Param("to_user")String nickname,@Param("title")String title,@Param("content")String content,HttpSession session){
        NutMap re=new NutMap();
        List<User> users=dao.query(User.class,Cnd.where("nickname","=",nickname));
        if(users.size()<1)
            return re.setv("ok",false).setv("msg","发送的对象不存在");
        else{
            Mail mail=new Mail();
            mail.setToUser(users.get(0).getUserId());
            mail.setFromUser((int)session.getAttribute("uid"));
            mail.setTitle(title);
            mail.setContent(content);
            mail.setInDate(new Date());
            mail.setNewMail(true);
            mail=dao.insert(mail);
            if(mail==null)
                return re.setv("ok",false).setv("msg","发送失败");
            return re.setv("ok",true).setv("msg","发送成功");
        }

    }


    @At
    @Ok("json:full")
    @GET
    @Api(name = "获取站内信列表",description = "fromUser如果为负数,则为系统消息,newmai代表是否是新邮件.users为用户昵称信息")
    public Object getmaillist(HttpSession session){
        List<Mail> mails = dao.query(Mail.class,Cnd.where("toUser","=",session.getAttribute("uid")).desc("mailId"));
        List<Integer> userId=new ArrayList<>();
        for(Mail mail:mails){
            if(mail.getFromUser()!=-1&&!userId.contains(mail.getFromUser())) userId.add(mail.getFromUser());
        }
        if(userId.size()>0){
            Sql sql= Sqls.create("select userId,nickname from user where userId in (@userId)");
            sql.setParam("userId",userId.toArray());
            sql.setCallback(Sqls.callback.records());
            dao.execute(sql);
            return new NutMap().setv("mails",mails).setv("users",sql.getResult());
        }
        return new NutMap().setv("mails",mails);
    }

}
